package org.fxcontainer.controls.ext
{
	import mx.containers.FormItem;
	import mx.controls.ComboBox;
	import mx.core.UIComponent;
	import mx.core.mx_internal;
	
	import org.fxcontainer.controls.IControl;
	
	public class FormItem extends mx.containers.FormItem implements IControl
		{
			
			/**
			 *  @private
			 *  The <code>Form</code> that owns this item.
			 */
			mx_internal var owner:Form;
			
			/**
			 * The control name. 
			 */
			private var _controlName:String;
			
			/**
			 * Flag to render <code>FormItem</code> in read-only mode. 
			 */
			private var _readOnly:Boolean = false;
			
			/**
			 * The <code>Validator</code>s list. 
			 */
			private var _validators :Array = [];
			
			/**
			 * Setable flag to render <code>FormItem</code> in read-only mode.
			 */
			private var _readOnlySet:Boolean = false;
			
			/**
			 *  Storage for the data property.
			 */
			private var _data:Object;
			
			public function FormItem()
			{
				super();
			}
			
			/**
			 * Retrieves control name if set, otherwise element ID. 
			 * @return control name
			 */
			public function controlName():String
			{
				if (_controlName == ""){
					_controlName = id;
				}
				return this._controlName;
			}
			
			public function set controlname(controlName:String):void
			{
				this._controlName = controlName;
			}
			
			public function set readOnly(value:Boolean):void
			{
				if( _readOnly==value ) return;
				_readOnly = value;
				_readOnlySet = true;
				commitReadOnly();
			}
			
			private function commitReadOnly():void
			{
				//if(_itemEditor==null) return;
				if(!_readOnlySet) return;
				_readOnlySet = false;
				/*if(Object(_itemEditor).hasOwnProperty("readOnly")){
				Object(_itemEditor).readOnly = _readOnly;
				_readOnlySet = false;
				}*/
			}
			
			public function get readOnly():Boolean
			{
				return _readOnly;
			}
			
			public function get validators() :Array {
				return _validators;
			}
			
			public function set validators(validatorItems :Array ): void {
				_validators = validatorItems;
			}
			
			override public function get data():Object
			{
				var children:Array = getChildren();
				for each(var child:* in children){
					
					if (child is ComboBox){
						_data = ComboBox(child).selectedItem;
						break;
					}
					if (child is UIComponent){
						_data = resolveData(child);
						break;
					}
				}
				return _data;
			}
			
			private function resolveData(component:UIComponent):Object
			{
				var result:Object = null;
				if (Object(component).hasOwnProperty("data")){
					result = Object(component).data;
				}
				if (null == result && Object(component).hasOwnProperty("text")){
					result = Object(component).text;
				}
				return result;
			}
		}
}